package cn.qqncn.quarz;

import cn.qqncn.client.EmailClient;
import cn.qqncn.entity.Capsule;
import cn.qqncn.service.CapsuleService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 这里定义具体的定时任务
 */
public class DateTimeJob extends QuartzJobBean {
    @Autowired
    EmailClient emailClient;

    //配置测试热刷新
//    @Value("${name}")
//    private String name;

    @Autowired
    CapsuleService capsuleService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取JobDetail中关联的数据
        String msg = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("msg");
        //获取当天需要发送邮件的任务
        List<Capsule> list = capsuleService.getTodayCapsule();
        for (int i = 0; i < list.size(); i++) {
            Capsule capsule = list.get(i);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
            String create_time = simpleDateFormat.format(capsule.getCreateTime());
            String result = emailClient.sendEmail(capsule.getContent(), capsule.getEmail(), create_time);
            //发送邮件成功则更新胶囊状态为已发送  即 1
            if (result.equals("true")){
                capsuleService.updateState(capsule.getId(),1);
            }else{
                //发送失败更新为未发送成功 即 2
                capsuleService.updateState(capsule.getId(),2);
            }
        }

        System.out.println("调度啦！！"+emailClient);
        System.out.println("current time :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "---" + msg);
    }
}